package tech.aistar.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tech.aistar.dto.Example;
import tech.aistar.dto.LevelWithName;
import tech.aistar.dto.MyWrongfirst;
import tech.aistar.dto.Wrong;
import tech.aistar.entity.*;
import tech.aistar.mapper.UserMapper;
import tech.aistar.service.*;
import tech.aistar.util.FileUtil;
import tech.aistar.util.Random;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LevelServiceImpl levelService;
    @Autowired
    private LevelNameServiceImpl levelNameService;
    @Autowired
    private TaskServiceImpl taskService;
    @Autowired
    private ExaScoreServiceImpl exaScoreService;
    @Autowired
    private ParperBankServiceImpl parperBankService;
    @Autowired
    private ExaInfoServiceImpl exaInfoService;
    @Autowired
    private WrongtopicServiceImpl wrongtopicService;
    @Autowired
    public ISinchoiceService sinchoiceService;
    @Autowired
    public IManchoiceService manchoiceService;
    @Autowired
    public ICompletionService completionService;
    @Autowired
    public IProgrammingService programmingService;
    @Autowired
    public CollectServiceImpl collectService;

    @Override
    public User findUserBynickname(String username) {
        return userMapper.findUserBynickname(username);
    }
    @Override
    public int register(User user) {
        return userMapper.insertUser(user);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }


    @Override
    public int uploadimg(String path, String nickname) {
        return userMapper.uploadimg(path, nickname);
    }

    @Override
    public String findusername(Long uid) {
        return userMapper.findusername(uid);
    }

    public User findUserById (Long uid){
        return userMapper.findUserById(uid);

    }
    @Override
    public List<Collect> fingByColId(Long uid) {
        return userMapper.fingByColId(uid);
    }

    public PageInfo<Collect> findcol(int pagenum,int pagesize,Long uid) {
        PageHelper.startPage(pagenum,pagesize);
        List<Collect> collects = collectService.findAllUserCol(String.valueOf(uid));
        PageInfo<Collect> pagetask = new PageInfo<>(collects);
        return pagetask;
    }

    //短信发送
    public String SendMessage (String phone){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4G1pNJxR2dKa1PWLbFL9", "MfR3HQweeXEbkuRfwQETdpEipV61ul");
        IAcsClient client = new DefaultAcsClient(profile);
        Random random = new Random();
        String code = random.getPwd();
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "悦知");
        request.putQueryParameter("TemplateCode", "SMS_202547147");
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return code;
    }
    //获取用户等级信息
    public LevelWithName getUserLevel (Long uid){
        Level level = levelService.findUserlevel(String.valueOf(uid));
        String levelName = levelNameService.findLevelName(level.getLevelUlevel());
        LevelWithName levelWithName = new LevelWithName(level.getLevelUintegral(), level.getLevelUlevel(), levelName);
        return levelWithName;
    }
    //获取用户任务信息
    public List<Task> getUserTask (String uid){
        return taskService.findUserTask(uid);
    }
    public PageInfo<Task> getUserTaskbyPage(int pagenum, int pagesize,String uid){
        PageHelper.startPage(pagenum,pagesize);
        List<Task> tasks = getUserTask(uid);
        PageInfo<Task> pagetask = new PageInfo<>(tasks);
        return pagetask;
    }
    //获取用户考试信息
    public List<Example> getUserExa (String uid){
        List<ExaScore> exaScores = exaScoreService.findUserexascore(uid);
//        System.out.println(exaScores);
        List<Example> examples = new ArrayList<>();
        for (ExaScore e : exaScores) {
            Example example = new Example();
            example.setExaScore(e.getExaScore());
            example.setExaTime(e.getExaTime());

            ExaInfo exaInfo = exaInfoService.findexa(String.valueOf(e.getTestId()));
//            System.out.println(exaInfo);
            example.setExaDate(new SimpleDateFormat("yyyy-MM-dd").format(exaInfo.getTestDate()));
            example.setParperName(parperBankService.findparpername(String.valueOf(exaInfo.getPaperId())));
//            System.out.println(e.getParperId());
//            System.out.println(parperBankService.findparpername(String.valueOf(e.getParperId())));
            examples.add(example);
        }
        System.out.println(examples);
        return examples;
    }

    @Override
    public List<MyWrongfirst> fingByUid(Long uid) {
        return userMapper.fingByUid(uid);
    }

    public List<Wrong> getUserWrongtopics(Long uid){
        List<MyWrongfirst> myWrongfirstList=this.fingByUid(uid);
        List<Wrong> wrongList = new ArrayList<>();
        for (MyWrongfirst e : myWrongfirstList){
            MyWrongfirst myWrongfirst = new MyWrongfirst();
            Wrong wrong = new Wrong();

            Long wrongType = e.getWrongType();//错题类型
            Long wrongQid = e.getWrongQid();//错题编号
            String wrongAnswer = e.getWrongAnswer();//用户答案
            //如果是单选题
            if (wrongType == 1){
                Sinchoice sinchoice = (Sinchoice) sinchoiceService.findById(wrongQid);

                wrong.setWrongType("单选题");//题目类型
                wrong.setWrongStem(sinchoice.getSinStem());//题目内容
                wrong.setWrongAnswer(wrongAnswer);//用户答案
                wrong.setTrueAnswer(sinchoice.getSinAnswer());//正确答案
                wrongList.add(wrong);            }
            //如果是多选题
            else if (wrongType == 2){
                Manchoice manchoice = (Manchoice) manchoiceService.findById(wrongQid);

                wrong.setWrongType("多选题");//题目类型
                wrong.setWrongStem(manchoice.getManStem());//题目内容
                wrong.setWrongAnswer(wrongAnswer);//用户答案
                wrong.setTrueAnswer(manchoice.getManAnswer());//正确答案
                wrongList.add(wrong);
            }
            //如果是填空题
            else if (wrongType == 3){
                Completion completion = (Completion) completionService.findById(wrongQid);

                wrong.setWrongType("填空题");//题目类型
                wrong.setWrongStem(completion.getComStem());//题目内容
                wrong.setWrongAnswer(wrongAnswer);//用户答案
                wrong.setTrueAnswer(completion.getComAnswer());//正确答案
                wrongList.add(wrong);
            }
            //如果是编程题
            else if (wrongType == 4){
                Programming programming= (Programming) programmingService.findById(wrongQid);

                wrong.setWrongType("编程题");//题目类型
                wrong.setWrongStem(programming.getProStem());//题目内容
                wrong.setWrongAnswer(wrongAnswer);//用户答案
                wrong.setTrueAnswer(programming.getProAnswer());//正确答案
                wrongList.add(wrong);
            }
        }
//        System.out.println(examples);
        return wrongList;
    }

    //上床头像到青牛云服务器

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    // 设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "TU-AkfiqlDMIJtGObYIpkmOklXXnVJEGPT5qe7kb";
    String SECRET_KEY = "X0am6fGBeP6EtEpQUMRlsuztsLOW15ZgCszAiWXg";
    // 要上传的空间
    String bucketname = "yuez";

    // 密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
    Configuration cfg = new Configuration(Zone.zone2());
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    // 测试域名，只有30天有效期
    private static String QINIU_IMAGE_DOMAIN = "http://qhwxnp6wj.hn-bkt.clouddn.com/";

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public String saveImage(MultipartFile file) throws IOException {

        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!FileUtil.isFileAllowed(fileExt)) {
                return null;
            }

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
//                System.out.println(QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key"));
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
//                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
//            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }

}

